package com.gusha.controller;

import java.math.BigDecimal;
import java.math.BigInteger;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import javax.persistence.metamodel.SetAttribute;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.gusha.config.SysOperateLog;
import com.gusha.utils.Constants;
import com.gusha.utils.FileUtils;
import com.gusha.utils.JsonResult;
import com.gusha.utils.WebValueUtil;
import com.gusha.utils.UpdateUtil;

import com.gusha.service.ProjectService;
import com.gusha.dao.ProjectDao;
import com.gusha.dao.SysAreaDao;
import com.gusha.dao.SysClassifyDao;
import com.gusha.model.Project;
import com.gusha.model.SysArea;
import com.gusha.model.SysClassify;
import com.gusha.model.User;


/**
 * @Created：2018-11-09 14:21:54
 * @Author LightSound的代码生成器
 * @Description:ProjectController控制类
 */
@Controller
@RequestMapping("/gx/project")
public class ProjectController {

	// 注入Dao
	@Autowired
	private ProjectDao projectDao;
	@Autowired
	private SysClassifyDao sysClassifyDao;
	@Autowired
	private SysAreaDao sysAreaDao;

	// 注入Service
	@Autowired
	private ProjectService projectService;
	//定义一个id
/*	private String id;*/
	// 查询列表
	@RequestMapping("list")
	@SysOperateLog(operate = "查看项目列表")
	public String list(Model model, HttpServletRequest request) {

		//请求参数
		String pageIndex = WebValueUtil.getWebValue(request, "pageIndex");
		String isChecked = WebValueUtil.getWebValue(request, "isChecked");
		String projectName = WebValueUtil.getWebValue(request, "projectName");

		String classifyId = WebValueUtil.getWebValue(request, "classifyId");
		String projectProvince = WebValueUtil.getWebValue(request, "projectProvince");
		String projectCity = WebValueUtil.getWebValue(request, "projectCity");
		String projectDistrict = WebValueUtil.getWebValue(request, "projectDistrict");
		        String moneyStart = WebValueUtil.getWebValue(request, "moneyStart");
		        String moneyEnd = WebValueUtil.getWebValue(request, "moneyEnd");

		//参数封装
		int pageNo = 0;
		if (StringUtils.isNotBlank(pageIndex)) {
			pageNo = Integer.parseInt(pageIndex);
		}
		Project project = new Project();
		if (StringUtils.isNotBlank(isChecked)) {
		}else {
			isChecked = "0";
		}
		project.setIsChecked(Integer.parseInt(isChecked));

		if (StringUtils.isNotBlank(projectName)) {
			project.setProjectName(projectName);
		}
		if (StringUtils.isNotBlank(classifyId)) {
			SysClassify classify = sysClassifyDao.getOne(new BigInteger(classifyId));
			project.setClassify(classify);
		}
		List<SysArea> listProvince = sysAreaDao.findAllByPCode("00");
		List<SysArea> listCity = new ArrayList<SysArea>();
		List<SysArea> listDistrict = new ArrayList<SysArea>();
		if (StringUtils.isNotBlank(projectProvince)) {
			SysArea province = sysAreaDao.findByCode(projectProvince);
			project.setProjectProvince(province);
			listCity = sysAreaDao.findAllByPCode(projectProvince);
		}
		if (StringUtils.isNotBlank(projectCity)) {
			SysArea city = sysAreaDao.findByCode(projectCity);
			project.setProjectCity(city);
			listDistrict = sysAreaDao.findAllByPCode(projectCity);
		}
		if (StringUtils.isNotBlank(projectDistrict)) {
			SysArea district = sysAreaDao.findByCode(projectDistrict);
			project.setProjectDistrict(district);
		}
		        if (StringUtils.isNotBlank(moneyStart)) {
		        	project.setMoneyStart(new BigDecimal(moneyStart));
		        }
		        if (StringUtils.isNotBlank(moneyEnd)) {
		        	project.setMoneyEnd(new BigDecimal(moneyEnd));
		        }

		//获取分页数据
		Sort sort = new Sort(Sort.Direction.DESC, "createTime");
		Pageable pageable = PageRequest.of(pageNo, Constants.DEFAULT_PAGESIZE, sort);
		Page<Project> page = projectService.findAll(pageable, project);

		model.addAttribute("page", page);
		model.addAttribute("isChecked", isChecked);
		model.addAttribute("projectName", projectName);
		model.addAttribute("classifyId", classifyId);
		model.addAttribute("projectProvince", projectProvince);
		model.addAttribute("projectCity", projectCity);
		model.addAttribute("projectDistrict", projectDistrict);
		model.addAttribute("moneyStart", moneyStart);
		model.addAttribute("moneyEnd", moneyEnd);
		        
		model.addAttribute("listProvince", listProvince);
		model.addAttribute("listCity", listCity);
		model.addAttribute("listDistrict", listDistrict);
		List<SysClassify> listClassify = sysClassifyDao.findAllByParentIdAndIsDelete(new BigInteger(Constants.CLASSIFY_PROJECT), Constants.RECOVERY);
		model.addAttribute("listClassify", listClassify);

		return "/admin/project/list";
	}

	// 进入添加页面
	@RequestMapping("toAdd")
	@SysOperateLog(operate = "进入项目添加页面")
	public String toAdd(Model model) {
		List<SysClassify> listParent = sysClassifyDao.findAllByParentIdAndIsDelete(new BigInteger(Constants.CLASSIFY_INFO),0);
		model.addAttribute("listParent", listParent);
		return "/admin/project/form";
	}

	// 进入编辑页面
	@RequestMapping("toEdit")
	@SysOperateLog(operate = "进入项目编辑页面")
	public String toEdit(Model model, HttpServletRequest request) {

		//请求参数
		String id = WebValueUtil.getWebValue(request, "id");

		if (StringUtils.isNotBlank(id)) {
			if(projectDao.existsById(new BigInteger(id))) {
				Project project = projectDao.getOne(new BigInteger(id));
				model.addAttribute("obj", project);
				
			}
		}        

		return "/admin/project/form";
	}
	
	// 保存
    @RequestMapping("save")
    @ResponseBody
    @SysOperateLog(operate = "保存项目信息")
    public JsonResult save(Project project) {
        JsonResult result = new JsonResult(false,"保存失败");
        if (project.getId() != null) {
            Project projectOld = projectDao.getOne(project.getId());
            UpdateUtil.copyNonNullProperties(project, projectOld);
        }
        projectDao.saveAndFlush(project);
        result.setFlag(true);
        result.setMsg("保存成功");

        return result;
    }

	// 保存
/*	@RequestMapping("save")
	@ResponseBody
	@SysOperateLog(operate = "保存项目信息")
	public JsonResult save(Project project,HttpServletRequest request) {
	project.setId(new BigInteger(id));
	Optional<Project> p= projectDao.findById(project.getId());
	project.setProjectImages(p.get().getProjectImages());
		String imageName = "";
		
		JsonResult result = new JsonResult(false,"保存失败");
		String projectIconOld = WebValueUtil.getWebValue(request, "projectIconOld");

		if(!projectIconOld.equals(project.getProjectIcon())) {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile file = multipartRequest.getFile("file");
			// 要上传的目标文件存放路径
			String newFileName = FileUtils.getFileName(file.getOriginalFilename());
			String imagePath = Constants.getFilePath("info")+newFileName;
			String localPath = Constants.IMAGE_LOCAL_PATH+Constants.getFilePath("info");
			FileUtils.upload(file, localPath, newFileName);
			project.setProjectIcon(imagePath);
		}


		projectDao.saveAndFlush(project);//保存一次
		result.setFlag(true);
		result.setMsg("保存成功");
		return result;
	}*/

/*	@RequestMapping(value="saveorupdate",method = RequestMethod.POST)
	@ResponseBody  
	public void upload_yz(Project project,MultipartFile [] files,HttpServletRequest request){
		String n="";//将所有图片拼接到一个字符串里
		for (MultipartFile file : files) {
			String req= file.getOriginalFilename();
			//     String newFileName = FileUtils.getFileName(file.getOriginalFilename());
			String imagePath = Constants.getFilePath("info")+req;
			String localPath = Constants.IMAGE_LOCAL_PATH+Constants.getFilePath("info");
			FileUtils.upload(file, localPath, req);
			n=n+"#"+imagePath;
		}
		String Strid=request.getParameter("id");	
		project.setId(new BigInteger(Strid));
		project.setProjectImages(n);
		String id= projectDao.saveAndFlush(project).getId().toString();//保存2次
		//给id设置参数
		setId(id);
	}*/

	// 删除
	@RequestMapping("delete")
	@ResponseBody
	@SysOperateLog(operate = "删除项目信息")
	public JsonResult delete(BigInteger id) {
		JsonResult result = new JsonResult(false,"删除失败");
		if (projectDao.existsById(id)) {
			Project project = projectDao.getOne(id);
			project.setIsDelete(Constants.DELETE);
			projectDao.saveAndFlush(project);
			result.setFlag(true);
			result.setMsg("删除成功");
		}else{
			result.setFlag(false);
			result.setMsg("该对象信息不存在");
			return result;
		}
		return result;
	}


	// 恢复
	@RequestMapping("recovery")
	@ResponseBody
	@SysOperateLog(operate = "恢复项目信息")
	public JsonResult recovery(BigInteger id) {
		JsonResult result = new JsonResult(false,"恢复失败");
		if (projectDao.existsById(id)) {
			Project project = projectDao.getOne(id);
			project.setIsDelete(Constants.RECOVERY);
			projectDao.saveAndFlush(project);
			result.setFlag(true);
			result.setMsg("恢复成功");
		}else{
			result.setFlag(false);
			result.setMsg("该对象信息不存在");
			return result;
		}
		return result;
	}
	//进入审核页面
	@RequestMapping("toCheck")
	@SysOperateLog(operate = "进入项目审核页面")
	public String toCheck(Model model,HttpServletRequest request) {
		String id = WebValueUtil.getWebValue(request, "id");
	
		
			Project obj=projectDao.getOne(new BigInteger(id));
			model.addAttribute("obj",obj);
		System.out.println(obj.getProjectImages());
		return "/admin/project/check";

	}
	
    // 审核
    @RequestMapping("doCheck")
    @ResponseBody
    @SysOperateLog(operate = "审核项目")
    public JsonResult doCheck(Project project) {
        JsonResult result = new JsonResult(false,"审核失败");
        if (project.getId() != null) {
            Project projectOld = projectDao.getOne(project.getId());
            UpdateUtil.copyNonNullProperties(project, projectOld);
        }
        projectDao.saveAndFlush(project);
        result.setFlag(true);
        result.setMsg("审核成功");

        return result;
    }

/*	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}*/

}
